<template>
  <div class="box">
    <div class="flex justify-between align-center mb-10">
      <div style="width: 500px">
        <a-radio-group v-model:value="modeType" @change="modeTypeChange">
          <a-radio-button value="channel">渠道申请审核<span
              v-if="channelCount!=0">（{{ channelCount }}）</span></a-radio-button>
          <a-radio-button value="channelCompany">渠道公司申请审核<span
              v-if="channelCompanyCount!=0">（{{ channelCompanyCount }}）</span></a-radio-button>
        </a-radio-group>
      </div>
      <a-row v-if="modeType=='channel'" class="flex-1 flex-end" wrap="true" :gutter="[9, 10]">
        <a-col
            :xl="$store.getters.isMobile ? 12 : 4"
            :lg="$store.getters.isMobile ? 12 : 6"
            :md="$store.getters.isMobile ? 12 : 8"
            :sm="12"
            :xs="$store.getters.isMobile ? 12 : 24"
        >
          <a-input
              class="w-100"
              v-model:value="searchParam.name"
              placeHolder="搜索联系人名称"
          ></a-input
          >
        </a-col>
        <a-col
            :xl="$store.getters.isMobile ? 12 : 4"
            :lg="$store.getters.isMobile ? 12 : 6"
            :md="$store.getters.isMobile ? 12 : 8"
            :sm="12"
            :xs="$store.getters.isMobile ? 12 : 24"
        >
          <a-input
              class="w-100"
              v-model:value="searchParam.phone"
              placeHolder="搜索联系人电话"
          ></a-input
          >
        </a-col>
        <a-col
            :xl="$store.getters.isMobile ? 12 : 4"
            :lg="$store.getters.isMobile ? 12 : 6"
            :md="$store.getters.isMobile ? 12 : 8"
            :sm="12"
            :xs="$store.getters.isMobile ? 12 : 24"
        >
          <a-select
              class="w-100"
              placeholder="选择渠道"
              :options="sourceOptions"
              v-model:value="searchParam.source"
          >
          </a-select>
        </a-col>
        <a-col
            :xl="$store.getters.isMobile ? 12 : 4"
            :lg="$store.getters.isMobile ? 12 : 6"
            :md="$store.getters.isMobile ? 12 : 8"
            :sm="12"
            :xs="$store.getters.isMobile ? 12 : 24"
        >
          <a-select
              class="w-100"
              placeholder="选择状态"
              :options="channelStatusOptions"
              v-model:value="searchParam.type"
          >
          </a-select>
        </a-col>
        <a-col>
          <div>
            <a-button style="margin-right: 10px" @click="reset"
            >重置
            </a-button>
            <a-button type="primary" @click="toSearch">搜索</a-button>
          </div>
        </a-col>
      </a-row>

      <a-row v-else class="flex-1 flex-end" wrap="true" :gutter="[9, 10]">
        <a-col
            :xl="$store.getters.isMobile ? 12 : 4"
            :lg="$store.getters.isMobile ? 12 : 6"
            :md="$store.getters.isMobile ? 12 : 8"
            :sm="12"
            :xs="$store.getters.isMobile ? 12 : 24"
        >
          <a-input
              class="w-100"
              v-model:value="searchChannelParam.head_name"
              placeHolder="负责人姓名"
          ></a-input
          >
        </a-col>
        <a-col
            :xl="$store.getters.isMobile ? 12 : 4"
            :lg="$store.getters.isMobile ? 12 : 6"
            :md="$store.getters.isMobile ? 12 : 8"
            :sm="12"
            :xs="$store.getters.isMobile ? 12 : 24"
        >
          <a-input
              class="w-100"
              v-model:value="searchChannelParam.head_phone"
              placeHolder="负责人手机号"
          ></a-input
          >
        </a-col>
        <a-col
            :xl="$store.getters.isMobile ? 12 : 4"
            :lg="$store.getters.isMobile ? 12 : 6"
            :md="$store.getters.isMobile ? 12 : 8"
            :sm="12"
            :xs="$store.getters.isMobile ? 12 : 24"
        >
          <a-select
              class="w-100"
              placeholder="选择渠道"
              :options="channelOptions"
              v-model:value="searchChannelParam.channel"
          >
          </a-select>
        </a-col>
        <a-col
            :xl="$store.getters.isMobile ? 12 : 4"
            :lg="$store.getters.isMobile ? 12 : 6"
            :md="$store.getters.isMobile ? 12 : 8"
            :sm="12"
            :xs="$store.getters.isMobile ? 12 : 24"
        >
          <a-select
              class="w-100"
              placeholder="选择状态"
              :options="statusOptions"
              v-model:value="searchChannelParam.approval_status"
          >
          </a-select>
        </a-col>
        <a-col>
          <div>
            <a-button style="margin-right: 10px" @click="reset"
            >重置
            </a-button>
            <a-button type="primary" @click="toSearch">搜索</a-button>
          </div>
        </a-col>
      </a-row>

    </div>


    <!--    渠道-->
    <a-table
        :columns="columns"
        :dataSource="tableData"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        bordered
        :scroll="{
        x: 'max-content',
      }"
        v-if="modeType=='channel'"
    >

      <template #bodyCell="{ column, record }">
        <template
            v-if="
            column.key == 'name' ||
            column.key == 'phone' ||
            column.key == 'village_name' ||
            column.key == 'created_at'
          "
        >
          {{ record[column.key] }}
        </template>
        <template v-if="column.key == 'source'">
          {{ record[column.key]?.source || "--" }}
        </template>

        <template v-if="column.key == 'extra'">
          <a-space>
            <a-image v-for="item in record?.extra" :width="60" :src="item"/>
          </a-space>
        </template>
        <template v-if="column.key == 'action'">
          <a-button type="link" @click="toDetail(record.id)"
                    v-if="!record.approval_id">详情
          </a-button>
          <a-button
              type="link"
              v-if="record.approval_id"
              @click="toApprovalDetail(record)"
          >审批详情
          </a-button
          >
        </template>
      </template>
    </a-table>

    <!--渠道公司-->
    <a-table :columns="companyColumns" :data-source="tableData" :pagination="pagination"
             :loading="loading"
             @change="handleTableChange" :scroll="{ x: 'max-content' }"
             v-if="modeType=='channelCompany'">
      <template #bodyCell="{column,record}">
        <template v-if="column.key=='address'">
          <span>{{ record?.address?.provinceName }}</span>
          <span>{{ record?.address?.cityName }}</span>
          <span>{{ record?.address?.districtName }}</span>
          <span>{{ record?.address?.streetName }}</span>
        </template>
        <template v-if="column.key=='isSign'">
          <a-tag v-if="record.is_sign==1" color="blue">已签署</a-tag>
          <a-tag v-if="record.is_sign==0">未签署</a-tag>
        </template>

        <template v-if="column.key=='approval_status'">
          <a-tag v-if="record.approval_status==1" color="blue">已审批</a-tag>
          <a-tag v-if="record.approval_status==0">待审批</a-tag>
          <a-tag v-if="record.approval_status==2" color="red">已拒绝</a-tag>
          <a-tag v-if="record.approval_status==3">已撤销</a-tag>
        </template>
        <template v-if="column.key=='action'">
          <a-space>

            <a-button type="link" @click="checkDetail(record.id)"
                      v-if="!record.approval_id">查看审批
            </a-button>
            <a-button type="link" @click="checkApproval(record.approval_id)"
                      v-if="record.approval_id">查看审批
            </a-button>
            <a-button type="link" @click="editCompany(record.id)"
                      :disabled="record.approval_status==0">编辑
            </a-button>
            <a-popconfirm
                title="确定删除该渠道公司?"
                ok-text="确认"
                cancel-text="取消"
                @confirm="deleteCompany(record.id)"
            >
              <a-button type="link" danger :disabled="record.approval_status==0">删除</a-button>
            </a-popconfirm>

          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 审批详情 -->
    <ChannelApprovalDetail
        :id="checkId"
        :causation="causation"
        :visible="visible"
        @closeDrawer="visible = false"
        @statusChange="handleStatusChange"
    />
    <!-- 详情 -->
    <ChannelInfoDetail
        :id="checkId"
        :visible="infoVisible"
        @cancel="infoVisible = false"
        @closeDetail="channelRefresh"
    />

    <ChannelCompanyEdit :visible="editVisible" :id="editId" @toClose="editVisible = false"
                        @onCommit="editSuccess"/>

    <ChannelCompanyDetail :id="editId" :visible="detailVisible" @closeDetail="companyRefresh"/>
  </div>
</template>

<script>
import {ref, reactive, toRefs, watch, computed} from "vue";
import request from "../../../../common/utils/request";
import ChannelApprovalDetail from "./ChannelApprovalDetail.vue";
import ChannelInfoDetail from "./ChannelInfoDetail.vue";
import channelCompany from '@/views/village/BusinessManage/modules/ChannelCompany.vue'
import {message} from 'ant-design-vue'
import ChannelCompanyEdit from '@/views/village/BusinessManage/modules/ChannelCompanyEdit.vue'
import ChannelCompanyDetail from "./ChannelCompanyDetail.vue"

export default {
  computed: {
    channelCompany() {
      return channelCompany
    }
  },
  props: {
    activeKey: {
      type: String,
      default: "",
    },
    sourceOptions: {
      type: Array,
      default: () => [],
    },
  },
  components: {
    ChannelCompanyEdit,
    ChannelApprovalDetail,
    ChannelInfoDetail,
    ChannelCompanyDetail,
  },
  setup(props, context) {
    const state = reactive({
      loading: false,
      checkId: 0,
      causation: 0,
      visible: false,
      infoVisible: false,
      modeType: "channel",
      channelCount: 0,
      channelCompanyCount: 0,
      channelOptions: [],
      editVisible: false,
      editId: 0,
      detailVisible: false,
    });


    const columns = [
      {title: "联系人名称", key: "name"},
      {title: "联系人电话", key: "phone"},
      {title: "所在区域", key: "address", dataIndex: "address"},
      {title: "渠道类型", key: "source"},
      {title: "来源", key: "causation_txt", dataIndex: "causation_txt"},
      {title: "关联项目", key: "village_name"},
      {title: "附件", key: "extra", width: "180"},
      {title: "申请时间", key: "created_at"},
      {
        title: "操作",
        key: "action",
      },
    ];

    const channelStatusOptions = [{
      label: "待审核",
      value: 2
    }, {
      label: "已拒绝",
      value: 4
    }, {
      label: "已撤销",
      value: 5
    }]

    const statusOptions = [{
      label: "待审核",
      value: 0
    }, {
      label: "已拒绝",
      value: 2
    }, {
      label: "已撤销",
      value: 3
    }]


    const searchParam = reactive({
      name: "",
      phone: "",
      source: undefined,
      type: 2,
    });


    const searchChannelParam = reactive({
      head_name: "",
      head_phone: "",
      channel: undefined,
      approval_status: 0,
    });

    const page = ref(1);
    const limit = ref(10);
    const total = ref(0);
    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      limit: limit.value,
      showSizeChanger: true,
    }));

    const tableData = ref([]);
    const getTableData = () => {
      state.loading = true;
      const param = {type: 2, page: page.value, pageSize: limit.value};
      Object.keys(searchParam).forEach((key) => {
        if (searchParam[key]) {
          param[key] = searchParam[key];
        }
      });
      request
          .get("/org", "/business/customer/channel", param)
          .then((res) => {
            console.log(res);
            tableData.value = res.list;
            total.value = res.total;
            state.channelCount = res.customerStatus0Count;
            state.channelCompanyCount = res.waitAuditCompanyCount;
            context.emit("numChange", res.customerStatus0Count + res.waitAuditCompanyCount);
          })
          .finally(() => {
            state.loading = false;
          });
    };
    getTableData();

    const getChannelCompanyTableList = () => {
      state.loading = true
      const params = {
        page: page.value,
        pageSize: limit.value,
      }
      console.log(searchChannelParam)
      for (const key in searchChannelParam) {
        if (key == 'channel' || key == 'approval_status') {
          if (searchChannelParam[key] != undefined) {
            params[key] = searchChannelParam[key]
          }
        } else {
          if (searchChannelParam[key]) {
            params[key] = searchChannelParam[key]
          }
        }
      }
      request.get("/org", "/business/customer/channel/channelCompanyList", params).then(res => {
        console.log(res)
        tableData.value = res.list
        total.value = res.total
        state.channelCount = res.customerStatus0Count;
        state.channelCompanyCount = res.waitAuditCompanyCount;
        context.emit("numChange", res.customerStatus0Count + res.waitAuditCompanyCount);
      }).finally(() => {
        state.loading = false
      });
    }


    const handleTableChange = (pager, filters, sorter) => {
      console.log(pager);
      page.value = pager.current;
      limit.value = pager.pageSize;
      if (state.modeType == 'channel') {
        getTableData()
      } else {
        getChannelCompanyTableList()
      }
    };


    // 查看详情
    const toDetail = (val) => {
      state.checkId = val;
      state.infoVisible = true;
    };
    // 查看详情
    const toApprovalDetail = (val) => {
      console.log(val.causation);
      state.checkId = val.approval_id;
      state.causation = val.causation;
      state.visible = true;
    };
    // 审批状态改变
    const handleStatusChange = () => {
      state.visible = false;
      getTableData();
    };
    const reset = () => {

      page.value = 1;
      if (state.modeType == "channel") {
        Object.keys(searchParam).forEach((key) => {
          searchParam[key] = key == "source" || key == "type" ? undefined : "";
        });
        searchParam.type = 2;
        getTableData()
      } else {
        Object.keys(searchChannelParam).forEach((key) => {
          searchChannelParam[key] = key == "source" || key == "approval_status" ? undefined : "";
        });
        searchChannelParam.approval_status = 0;
        getChannelCompanyTableList()
      }
    };

    const toSearch = () => {
      page.value = 1;
      if (state.modeType == "channel") {
        getTableData()
      } else {
        getChannelCompanyTableList()
      }
    };

    watch(
        () => props.activeKey,
        (val) => {
          if (val == "review") {
            if (state.modeType == "channel") {
              getTableData()
            } else {
              getChannelCompanyTableList()
            }
          }
          ;
        }
    );

    const modeTypeChange = (e) => {
      const mode = e.target.value;
      page.value = 1;
      tableData.value = []
      if (mode == "channel") {
        getTableData()
      } else {
        getChannelCompanyTableList()
      }
    }

    const channelRefresh = () => {
      state.infoVisible = false
      getTableData()
    }

    const companyRefresh = () => {
      state.detailVisible = false
      state.editId = 0
      getChannelCompanyTableList()
    }

    const checkDetail = (val) => {
      state.editId = val
      state.detailVisible = true
    }

    const checkApproval = (val) => {
      //查看审批
      state.checkId = val;
      state.causation = 1;
      state.visible = true;
    }

    const editCompany = (val) => {
      console.log(val)
      state.editId = val
      state.editVisible = true
    }

    const deleteCompany = (val) => {
      console.log(val)
      request.del("/org", "/business/customer/channel/channelCompanyDel", {id: val}).then(res => {
        message.success("删除成功")
        getChannelCompanyTableList()
      })
    }

    const editSuccess = () => {
      state.editVisible = false
      getChannelCompanyTableList()
    }

    const companyColumns = [
      {
        title: "公司名称",
        key: "name",
        dataIndex: "name",
        width: 200,
        fixed: 'left'
      }, {
        title: "负责人",
        key: "head_name",
        dataIndex: "head_name"
      }, {
        title: "负责人号码",
        key: "head_phone",
        dataIndex: "head_phone"
      }, {
        title: "税号",
        key: "tax_id",
        dataIndex: "tax_id"
      }, {
        title: "所在地",
        key: "address",
        dataIndex: "address",
        width: 200
      }, {
        title: "开户行",
        key: "opening_bank",
        dataIndex: "opening_bank"
      }, {
        title: "收款账号",
        key: "receiving_account",
        dataIndex: "receiving_account"
      }, {
        title: "是否签订合作协议",
        key: "isSign",
        width: 180
      }, {
        title: "协议签订日",
        key: "sign_date",
        dataIndex: "sign_date",
        width: 150
      }, {
        title: "协议到期日",
        key: "expire_date",
        dataIndex: "expire_date",
        width: 150
      }, {
        title: "审核状态",
        key: "approval_status",
        dataIndex: "approval_status",
        width: 180
      }, {
        title: "创建时间",
        key: "created_at",
        dataIndex: "created_at",
        width: 180
      }, {
        title: "操作",
        key: "action",
        dataIndex: "",
        fixed: 'right'
      }

    ]

    return {
      ...toRefs(state),
      ...toRefs(searchParam),
      columns,
      tableData,
      pagination,
      handleTableChange,
      toDetail,
      toApprovalDetail,
      handleStatusChange,
      reset,
      toSearch,
      modeTypeChange,
      ...toRefs(searchChannelParam),
      companyColumns,
      editCompany,
      deleteCompany,
      checkDetail,
      editSuccess,
      checkApproval,
      companyRefresh,
      channelRefresh,
      statusOptions,
      searchChannelParam,
      searchParam,
      channelStatusOptions,


    };
  },
};
</script>

<style lang="less" scoped>
.box {
  padding: 10px;
}

.w-100 {
  width: 100%;
}
</style>
